const dbApi = require('../models/db')
const jwt = require('../utils/jwt')
const { uuid } = require('../config/config.default')
const { body } = require('express-validator')
// 搜索建议
exports.getSearchSuggest = async (req, res, next) => {
  const { q } = req.query
  // 总共十条
  // 关于频道类型两条
  // 标题五条
  // 用户昵称 五条
  // 一个搜索表 按照值开头的搜索出最高十条，

  // 简单点
  // 按照用户传入的值，以这个值开头的点击量最高的十个文章标题
  // 每次搜索 应该添加记录到数据库
  const sql = `SELECT id,title FROM articles WHERE title LIKE '${q}%' GROUP BY title ORDER BY clicks DESC LIMIT 0,10`
  try {
    const data = await dbApi.query(sql)
    res.status(200).json({
      data,
      message: 'succsed'
    })
  } catch (error) {
    next(error)
  }
}

// 搜索结果
exports.getSearchResults = async (req, res, next) => {
  // 用户登录，把搜索记录一并记到数据库
  let { q, page } = req.query
  let token = req.headers.authorization
  token = token ? token.split('Bearer ')[1] : null
  try {
    if (token) {
      // 已登录
      const userInfo = await jwt.verify(token, uuid)
      const sqlSearch = `INSERT INTO searchhistory (search_text,username)
                         VALUES('${q}','${userInfo.uid}')`
      await dbApi.query(sqlSearch)
    }
    // 是否登录，都要返回搜索结果
    page = page > 1 ? (page - 1) * 10 : 0
    const sql = `SELECT id,title FROM articles WHERE title LIKE '%${q}%' 
                ORDER BY clicks DESC LIMIT ${page},10`
    const sql2 = `SELECT COUNT(*) as count FROM articles WHERE title LIKE '%${q}%'`
    const data = await dbApi.query(sql)
    const search_count = await dbApi.query(sql2)
    res.status(200).json({
      data,
      count: search_count[0].count,
      message: 'succsed'
    })
  } catch (error) {
    next(error)
  }
}

// 获取用户搜索历史
exports.getSearchHistory = async (req, res, next) => {
  const sql = `SELECT search_text FROM searchhistory 
                WHERE username = '${req.user.username}'  
                GROUP BY search_text ORDER BY search_time ASC  LIMIT 0,15`
  try {
    const data = await dbApi.query(sql)
    const arr = []
    data.forEach((item) => {
      arr.push(item.search_text)
    })
    res.status(200).json({
      data: arr,
      message: 'succsed'
    })
  } catch (error) {
    next(error)
  }
}
